package cn.edu.njnu.opengmpback.common.JSch;

import com.jcraft.jsch.JSch;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import com.jcraft.jsch.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Component
public class JSchConnectionManager {
    private static final Logger logger = LoggerFactory.getLogger(JSchConnectionManager.class);

    @Value("${dockerServerUserName}")
    private  String username;

    @Value("${dockerServerIp}")
    private  String host;

    @Value("${dockerServerPsd}")
    private  String password;

    private Session session;

    @PostConstruct
    public void init() {
        try {
            JSch jsch = new JSch();
            session = jsch.getSession(username, host, 22);
            session.setPassword(password);

            // 配置连接属性
            java.util.Properties config = new java.util.Properties();
            config.put("StrictHostKeyChecking", "no");
            config.put("PreferredAuthentications", "publickey,keyboard-interactive,password");
            session.setConfig(config);

            // 连接到远程服务器
            session.connect(60000); // 设置5秒超时时间
            logger.info("JSch Session connected.");
        } catch (Exception e) {
            // 仅记录错误，不抛出异常，避免阻止应用程序启动
            logger.error("Failed to connect to SSH server: {}", e.getMessage());
            logger.debug("SSH connection error details", e);
            e.printStackTrace();
        }
    }

    @PreDestroy
    public void cleanup() {
        if (session != null && session.isConnected()) {
            session.disconnect();
            logger.info("JSch Session disconnected.");
        }
    }

    public Session getSession() {
        if(session == null || !session.isConnected()) {
            try {
                init();
            } catch (Exception e) {
                logger.error("Failed to initialize SSH session: {}", e.getMessage());
                return null;
            }
        }
        return session;
    }
}